package com.ruoyi.finance.livestreaming.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfoDefined;
import com.ruoyi.finance.rules.entity.SzUser;
import com.ruoyi.finance.rules.task.SZRuleCache;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.finance.livestreaming.service.IFiDigitalLivestreamingService;
import com.ruoyi.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 数字直播Controller
 * 
 * @author wangmh
 * @date 2023-09-17
 */
@RestController
@RequestMapping("/finance/livestreaming")
public class FiDigitalLivestreamingController extends BaseController
{

    @Autowired
    private IFiDigitalLivestreamingService fiDigitalLivestreamingService;

    @Autowired
    private SZRuleCache szRuleCache;


    /**
     * 查询数字直播列表
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:list')")
    @GetMapping("/list")
    public TableDataInfoDefined list(SzUser szUser) {
        List<SzUser> AllList = fiDigitalLivestreamingService.selectFiDigitalLivestreamingList(szUser);
        startPage();
        List<SzUser> list = fiDigitalLivestreamingService.selectFiDigitalLivestreamingList(szUser);
        //计算钱包余额，钱包提现余额
        BigDecimal szWalletBalanceSum=BigDecimal.ZERO;
        BigDecimal szWithdrawalBalanceSum=BigDecimal.ZERO;
        for (SzUser user : AllList) {
            if ("平台用户".equals(user.getAccountType())){
                continue;
            }
            szWalletBalanceSum= Objects.isNull(user.getSzWalletBalance())?BigDecimal.ZERO:user.getSzWalletBalance().add(szWalletBalanceSum);
            szWithdrawalBalanceSum= Objects.isNull(user.getSzWithdrawalBalance())?BigDecimal.ZERO:user.getSzWithdrawalBalance().add(szWithdrawalBalanceSum);
        }
        TableDataInfoDefined rspData = new TableDataInfoDefined();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setSzWalletBalanceSum(szWalletBalanceSum);
        rspData.setSzWithdrawalBalanceSum(szWithdrawalBalanceSum);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 导出数字直播列表
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:export')")
    @Log(title = "数字直播用户数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SzUser szUser) {
        List<SzUser> list = fiDigitalLivestreamingService.selectFiDigitalLivestreamingList(szUser);
        ExcelUtil<SzUser> util = new ExcelUtil<SzUser>(SzUser.class);
        return util.exportExcel(list, "数字人直播用户数据");
    }

    /**
     * 购买数字直播
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:buy')")
    @Log(title = "购买数字直播", businessType = BusinessType.INSERT)
    @PostMapping("/buyLivestreaming")
    public AjaxResult buyLivestreaming(String userId, String parentId) {
        if (StringUtil.isEmpty(parentId) || "null".equals(parentId) || "undefined".equals(parentId)){
            return fiDigitalLivestreamingService.buyProduct(userId);
        }else{
            return fiDigitalLivestreamingService.buyProductByInvite(userId, parentId);
        }
    }


    /**
     * 购买数字直播 - 抵扣支付
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:deductionBuy')")
    @Log(title = "购买数字直播 - 抵扣支付", businessType = BusinessType.INSERT)
    @PostMapping("/deductionBuyLivestreaming")
    public AjaxResult deductionBuyLivestreaming(String userId, String parentId, BigDecimal amount, BigDecimal deductionAmount) {
        if (StringUtil.isEmpty(userId)){
            return AjaxResult.error();
        }

        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0){
            return AjaxResult.error("支付金额不能小于0！");
        }

        if (amount.compareTo(szRuleCache.getOtherRule().getPricing()) > 0){
            return AjaxResult.error("支付金额超过正常购买金额，请通过《购买产品(免支付)》按钮操作");
        }

        if (StringUtil.isEmpty(parentId) || "null".equals(parentId) || "undefined".equals(parentId)){
            return fiDigitalLivestreamingService.deductionBuyProduct(userId, amount, deductionAmount);
        }else{
            return fiDigitalLivestreamingService.deductionBuyProductByInvite(userId, parentId, amount, deductionAmount);
        }
    }


    /**
     * 数字直播对冲
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:mutualRecharge')")
    @Log(title = "数字直播对冲产品", businessType = BusinessType.UPDATE)
    @PostMapping("/mutualRecharge")
    public AjaxResult mutualRecharge(String fromUser, String toUser){
        if (StringUtil.isNotEmpty(fromUser) && StringUtil.isNotEmpty(toUser)){
            return fiDigitalLivestreamingService.mutualRecharge(fromUser, toUser);
        }else{
            return AjaxResult.error();
        }
    }

    /**
     * 数字直播对冲提现余额
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:mutualRechargeBalance')")
    @Log(title = "数字直播对冲提现余额", businessType = BusinessType.UPDATE)
    @PostMapping("/mutualRechargeBalance")
    public AjaxResult mutualRechargeBalance(String fromUser, String toUser, BigDecimal money, String paymentPassword){
        if (StringUtil.isNotEmpty(fromUser) && StringUtil.isNotEmpty(toUser) && StringUtil.isNotEmpty(paymentPassword) && money != null){
            return fiDigitalLivestreamingService.mutualRechargeBalance(fromUser, toUser, money, paymentPassword);
        }else{
            return AjaxResult.error();
        }
    }


    /**
     * 获取数字直播用户邀请人
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:userInviteTree')")
    @PostMapping(value = "/userInviteTree")
    public AjaxResult userInviteTree(Long userId) {
        return AjaxResult.success(fiDigitalLivestreamingService.userInviteTree(userId));
    }


    /**
     * 用户购买记录
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:purchaseRecordToAdmin')")
    @PostMapping(value = "/purchaseRecordToAdmin")
    public AjaxResult purchaseRecordToAdmin(Long userId) {
        Map<String, Object> stringObjectMap = fiDigitalLivestreamingService.purchaseRecord(userId);
        return AjaxResult.success(stringObjectMap);
    }


    /**
     * 用户余额细明
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:balanceDetailAdmin')")
    @PostMapping(value = "/balanceDetailAdmin")
    public AjaxResult balanceDetailAdmin(Long userId) {
        Map<String, Object> stringObjectMap = fiDigitalLivestreamingService.balanceDetailAdmin(userId);
        return AjaxResult.success(stringObjectMap);
    }

    /**
     * 用户可提现余额细明
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:withdrawalBalance')")
    @PostMapping(value = "/withdrawalBalance")
    public AjaxResult withdrawalBalance(Long userId) {
        Map<String, Object> stringObjectMap = fiDigitalLivestreamingService.withdrawalBalance(userId);
        return AjaxResult.success(stringObjectMap);
    }


    /**
     * 扫码支付 创建订单
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:createOrder')")
    @PostMapping(value = "/createOrder")
    public AjaxResult createOrder(String userId, String parentId){
        if (StringUtil.isEmpty(userId)){
            return AjaxResult.error();
        }
        return fiDigitalLivestreamingService.createOrder(userId, parentId);
    }


    @ApiOperation(value = "个人中心-购买数字人直播-订单轮询")
    @PostMapping("/orderPolling")
    public AjaxResult orderPolling(String orderId , HttpServletRequest request){
        return fiDigitalLivestreamingService.orderPolling(orderId, request);
    }


    /**
     * H5支付 创建订单
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:createOrderH5')")
    @RequestMapping(value = "/createOrderH5")
    public AjaxResult createOrderH5(String userId, String parentId, HttpServletRequest request, HttpServletResponse response){
//        if (StringUtil.isEmpty(userId)){
//            return AjaxResult.error();
//        }
        return fiDigitalLivestreamingService.createOrderH5(userId, parentId, request, response);
    }


    /**
     * 冻结/启用
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('finance:livestreaming:frozenOrEnable')")
    @Log(title = "数字直播-冻结/开启", businessType = BusinessType.UPDATE)
    @PostMapping("/frozenOrEnable")
    public AjaxResult frozenOrEnable(Long id, String type) {
        return fiDigitalLivestreamingService.frozenOrEnable(id, type);
    }

}
